package com.applancer.fragment;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.Header;

import uk.co.senab.actionbarpulltorefresh.library.ActionBarPullToRefresh;
import uk.co.senab.actionbarpulltorefresh.library.PullToRefreshLayout;
import uk.co.senab.actionbarpulltorefresh.library.listeners.OnRefreshListener;
import android.app.Activity;
import android.app.Fragment;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Typeface;
import android.os.Bundle;
import android.os.Handler;
import android.support.v13.app.FragmentStatePagerAdapter;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewConfiguration;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ExpandableListView;
import android.widget.ExpandableListView.OnChildClickListener;
import android.widget.ExpandableListView.OnGroupClickListener;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ProgressBar;

import com.applancer.adapter.HomeFeedAdapter;
import com.applancer.appInterface.ViewPagerEventInteface;
import com.applancer.dataprovider.DataType.Type;
import com.applancer.delegate.NewFeedDelegate;
import com.applancer.model.FeedModel;
import com.applancer.model.GeneralModel;
import com.applancer.nativecmsflip.FeedDetailActivity;
import com.applancer.nativecmsflip.R;
import com.applancer.parser.GeneralParser;
import com.applancer.provider.StringUtils;
import com.applancer.ui.CustomViewPager;
import com.loopj.android.http.AsyncHttpResponseHandler;

public class FeedHomeFragment extends FeedGeneralFragment implements
		OnRefreshListener {

	protected NewFeedDelegate delegate;
	protected ExpandableListView listView;
	protected HomeFeedAdapter adapter;
	protected List<GeneralModel> listData;
	protected String title;
	protected ProgressBar indicator_loading_feed;
	protected ImageButton indicator_refresh_feed;
	private PullToRefreshLayout mPullToRefreshLayout;
	protected int topmostListView;
	protected View header;
	protected CustomViewPager mPager;
	protected FragmentStatePagerAdapter mPagerAdapter;
	protected Button bt_feature;
	protected Button bt_mostview;
	protected List<GeneralModel> listFeedFeature;
	protected List<GeneralModel> listFeedMostView;
	protected List<GeneralModel> listPager;

	protected Boolean passGetFeature;
	protected Boolean passGetMostView;
	protected Boolean passGetHomeData;

	protected ImageView arrow_slide_left;
	protected ImageView arrow_slide_right;

	protected ViewPagerEventInteface viewPagerCallback;

	public FeedHomeFragment(String i, String title, NewFeedDelegate del) {

		delegate = del;
		id = i;
		this.title = title;

	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {

		contentView = inflater.inflate(R.layout.feed_home_fragment, null);
		header = inflater.inflate(R.layout.home_header, null);
		header.setVisibility(View.GONE);
		return contentView;

	}

	@Override
	public void onAttach(Activity activity) {

		try {
			viewPagerCallback = (ViewPagerEventInteface) activity;
		} catch (ClassCastException e) {
			throw new ClassCastException(
					"Activity must implement NavigationDrawerCallbacks.");
		}

		super.onAttach(activity);
	}

	@Override
	protected void initial() {
		super.initial();

		passGetFeature = false;
		passGetMostView = false;
		passGetHomeData = false;

		arrow_slide_left = (ImageView) header
				.findViewById(R.id.arrow_slide_left);
		arrow_slide_right = (ImageView) header
				.findViewById(R.id.arrow_slide_right);

		listFeedFeature = new ArrayList<GeneralModel>();
		listFeedMostView = new ArrayList<GeneralModel>();
		listPager = new ArrayList<GeneralModel>();

		bt_feature = (Button) header.findViewById(R.id.bt_feature);
		bt_mostview = (Button) header.findViewById(R.id.bt_mostview);

		bt_feature.setOnClickListener(featureClick);
		bt_mostview.setOnClickListener(mostViewClick);

		listData = new ArrayList<GeneralModel>();
		adapter = new HomeFeedAdapter(contentView.getContext(), listData);
		listView = (ExpandableListView) contentView
				.findViewById(R.id.list_feed);
		indicator_loading_feed = (ProgressBar) contentView
				.findViewById(R.id.indicator_loading_feed);
		indicator_refresh_feed = (ImageButton) contentView
				.findViewById(R.id.indicator_refresh_feed);
		parser = GeneralParser.createInstance(Type.Home);
		mPullToRefreshLayout = (PullToRefreshLayout) contentView
				.findViewById(R.id.ptr_layout);

		mPager = (CustomViewPager) header.findViewById(R.id.pagerNews);
		mPager.setOffscreenPageLimit(1);

		mPagerAdapter = new FragmentStatePagerAdapter(getActivity()
				.getFragmentManager()) {

			@Override
			public int getCount() {
				return listPager.size();
			}

			@Override
			public Fragment getItem(int position) {
				return PageFragment.newInstance(listPager.get(position));
			}
		};
		mPager.setAdapter(mPagerAdapter);

	}

	@Override
	protected void execution() {
		super.execution();

		arrow_slide_left.setVisibility(View.GONE);

		bt_feature.setTypeface(bt_feature.getTypeface(), Typeface.BOLD);

		mPager.setOnTouchListener(new OnTouchListener() {
			private float pointX;
			private float pointY;
			private int tolerance = 50;

			@Override
			public boolean onTouch(View v, MotionEvent event) {
				switch (event.getAction()) {
				case MotionEvent.ACTION_MOVE:
					return false; // This is important, if you return TRUE the
									// action of swipe will not take place.
				case MotionEvent.ACTION_DOWN:
					pointX = event.getX();
					pointY = event.getY();
					viewPagerCallback.onFreezeViewPager();

					Log.e("viewpager", "block");
					// mPager.setPagingEnabled(false);
					break;
				case MotionEvent.ACTION_UP:
					Log.e("viewpager", "release");

					// mPager.setPagingEnabled(true);
					boolean sameX = pointX + tolerance > event.getX()
							&& pointX - tolerance < event.getX();
					boolean sameY = pointY + tolerance > event.getY()
							&& pointY - tolerance < event.getY();
					if (sameX && sameY) {
						// The user "clicked" certain point in the screen or
						// just returned to the same position an raised the
						// finger
					}
				}
				return false;
			}
		});

		ActionBarPullToRefresh.from(getActivity())
				.theseChildrenArePullable(listView).listener(this)
				.setup(mPullToRefreshLayout);

		listView.setOnGroupClickListener(groupClick);
		listView.setOnChildClickListener(childClick);
		listView.setVerticalScrollBarEnabled(false);
		listView.setOnScrollListener(scrollListener);
		listView.setAdapter(adapter);

		mPager.setOnPageChangeListener(onpagechange);

		listView.addHeaderView(header);

		fitListView();

		indicator_refresh_feed.setOnClickListener(refreshClick);
		indicator_loading_feed.setVisibility(View.VISIBLE);
		indicator_refresh_feed.setVisibility(View.GONE);
		getFeed();
		getFeature();
		getMostView();
	}

	OnPageChangeListener onpagechange = new OnPageChangeListener() {

		@Override
		public void onPageSelected(int arg0) {

			if (listPager.size() == 1) {
				arrow_slide_left.setVisibility(View.GONE);
				arrow_slide_right.setVisibility(View.GONE);
				return;
			}

			if (arg0 == 0) {
				arrow_slide_left.setVisibility(View.GONE);
				arrow_slide_right.setVisibility(View.VISIBLE);
			}

			if (arg0 > 0 && arg0 < listPager.size() - 1) {
				arrow_slide_left.setVisibility(View.VISIBLE);
				arrow_slide_right.setVisibility(View.VISIBLE);
			}

			if (arg0 == listPager.size() - 1) {
				arrow_slide_left.setVisibility(View.VISIBLE);
				arrow_slide_right.setVisibility(View.GONE);
			}

			Log.d("viewpager", "page change");

		}

		@Override
		public void onPageScrolled(int arg0, float arg1, int arg2) {
			mPullToRefreshLayout.setEnabled(false);
			//viewPagerCallback.onFreezeViewPager();
			Log.d("viewpager", "page scroll");
		}

		@Override
		public void onPageScrollStateChanged(int arg0) {
			viewPagerCallback.onReleaseViewPager();
			mPullToRefreshLayout.setEnabled(true);
			Log.d("viewpager", "page state change");
		}
	};

	private void getFeature() {
		dataProvider.getFeature(featureHandler, 0);
	}

	private void getMostView() {
		dataProvider.getMostView(mostViewHandler);
	}

	OnClickListener featureClick = new OnClickListener() {

		@Override
		public void onClick(View v) {
			arrow_slide_left.setVisibility(View.GONE);
			bt_feature.setTypeface(bt_feature.getTypeface(), Typeface.BOLD);
			bt_mostview.setTypeface(Typeface.DEFAULT, Typeface.NORMAL);

			listPager.clear();
			listPager.addAll(listFeedFeature);
			mPagerAdapter.notifyDataSetChanged();
			mPager.setAdapter(mPagerAdapter);
		}
	};

	OnClickListener mostViewClick = new OnClickListener() {

		@Override
		public void onClick(View v) {
			arrow_slide_left.setVisibility(View.GONE);
			bt_mostview.setTypeface(bt_mostview.getTypeface(), Typeface.BOLD);
			bt_feature.setTypeface(Typeface.DEFAULT, Typeface.NORMAL);

			listPager.clear();
			listPager.addAll(listFeedMostView);
			mPagerAdapter.notifyDataSetChanged();
			mPager.setAdapter(mPagerAdapter);

		}
	};

	OnClickListener refreshClick = new OnClickListener() {

		@Override
		public void onClick(View v) {
			indicator_loading_feed.setVisibility(View.VISIBLE);
			indicator_refresh_feed.setVisibility(View.GONE);
			(new Handler()).postDelayed(new Runnable() {

				@Override
				public void run() {
					getFeed();
					getFeature();
					getMostView();
				}
			}, 2000);

		}
	};

	private void fitListView() {
		int currentapiVersion = android.os.Build.VERSION.SDK_INT;
		boolean hasMenuKey = ViewConfiguration.get(contentView.getContext())
				.hasPermanentMenuKey();
		if (currentapiVersion >= 19) {
			Resources r = getResources();

			int px = (int) r.getDimension(R.dimen.padding_materio);
			int statusbar_heigh = StringUtils.getStatusBarHeight(getActivity());
			int actionbar_heigh = StringUtils.getActionbarHeight(getActivity());

			topmostListView = px + statusbar_heigh + actionbar_heigh;

			listView.setPadding(
					px,
					topmostListView,
					px,
					px
							+ (!hasMenuKey ? StringUtils
									.getNavigationBarHeigh(getActivity()) : 0));
		}

	}

	public void onConfigurationChanged(
			android.content.res.Configuration newConfig) {
		super.onConfigurationChanged(newConfig);
		fitListView();
		adapter.notifyDataSetChanged();
		listView.invalidateViews();
	};

	OnItemClickListener itemClick = new OnItemClickListener() {

		@Override
		public void onItemClick(AdapterView<?> parent, View view, int position,
				long id) {

			GeneralModel model = (GeneralModel) parent.getAdapter().getItem(
					position);

			Intent intent = new Intent(contentView.getContext(),
					FeedDetailActivity.class);
			intent.putExtra("model", model);
			intent.putExtra("title", title);

			contentView.getContext().startActivity(intent);
			if (getActivity() != null)
				getActivity().overridePendingTransition(R.anim.slide_left_in,
						R.anim.slide_left_out);
		}
	};

	OnGroupClickListener groupClick = new OnGroupClickListener() {

		@Override
		public boolean onGroupClick(ExpandableListView parent, View v,
				int groupPosition, long id) {
			GeneralModel model = (GeneralModel) parent
					.getExpandableListAdapter().getGroup(groupPosition);

			Intent intent = new Intent(contentView.getContext(),
					FeedDetailActivity.class);

			ArrayList<FeedModel> lmodeldata = new ArrayList<FeedModel>();
			int curIndex = 0;
			for (int i = 0; i < listData.size(); i++) {
				if (((FeedModel) model).getId().equals(
						((FeedModel) listData.get(i)).getId())) {
					curIndex = i;
				}
				lmodeldata.add((FeedModel) listData.get(i));
			}

			intent.putExtra("lmodel", lmodeldata);
			intent.putExtra("index", curIndex);
			intent.putExtra("title", title);

			contentView.getContext().startActivity(intent);
			if (getActivity() != null)
				getActivity().overridePendingTransition(R.anim.slide_left_in,
						R.anim.slide_left_out);
			return true;
		}
	};

	OnChildClickListener childClick = new OnChildClickListener() {

		@Override
		public boolean onChildClick(ExpandableListView parent, View v,
				int groupPosition, int childPosition, long id) {
			GeneralModel model = (GeneralModel) parent
					.getExpandableListAdapter().getChild(groupPosition,
							childPosition);

			Intent intent = new Intent(contentView.getContext(),
					FeedDetailActivity.class);
			ArrayList<FeedModel> lmodeldata = new ArrayList<FeedModel>();
			int curIndex = 0;
			for (int i = 0; i < listData.size(); i++) {
				if (((FeedModel) model).getId().equals(
						((FeedModel) listData.get(i)).getId())) {
					curIndex = i;
				}
				lmodeldata.add((FeedModel) listData.get(i));
			}

			intent.putExtra("lmodel", lmodeldata);
			intent.putExtra("index", curIndex);
			intent.putExtra("title", title);

			contentView.getContext().startActivity(intent);
			if (getActivity() != null)
				getActivity().overridePendingTransition(R.anim.slide_left_in,
						R.anim.slide_left_out);

			return false;
		}
	};

	OnScrollListener scrollListener = new OnScrollListener() {

		@Override
		public void onScrollStateChanged(AbsListView view, int scrollState) {

		}

		@Override
		public void onScroll(AbsListView view, int firstVisibleItem,
				int visibleItemCount, int totalItemCount) {

			if (firstVisibleItem == 0) {
				View viewChild = listView.getChildAt(0);
				if (viewChild != null) {
					int i = viewChild.getTop();

					if (i == topmostListView) {
						mPullToRefreshLayout.setEnabled(true);
					} else {
						mPullToRefreshLayout.setEnabled(false);
					}
				}

			}

		}
	};

	AsyncHttpResponseHandler handler = new AsyncHttpResponseHandler() {
		public void onStart() {
			Log.d(this.getClass().toString(), "getFeed start");

		};

		@Override
		public void onSuccess(int arg0, Header[] arg1, byte[] response) {

			String result = new String(response);
			parser = GeneralParser.createInstance(Type.Home);
			List<GeneralModel> newData = parser.parseData(result);

			if (newData.size() == 0)
				return;

			listData.clear();
			listData.addAll(newData);

		}

		@Override
		public void onFailure(int arg0, Header[] arg1, byte[] arg2,
				Throwable arg3) {

		}

		public void onFinish() {
			passGetHomeData = true;
			loadDataSuccess();

			if (mPullToRefreshLayout != null) {
				mPullToRefreshLayout.setRefreshComplete();
				viewPagerCallback.onReleaseViewPager();
			}
		};

	};

	public void getFeed() {
		Log.d(this.getClass().toString(),
				"getFeed" + "with size : " + listData.size());
		if (!dataProvider.getHomeData(handler) && listData.size() == 0) {
			indicator_loading_feed.setVisibility(View.GONE);
			indicator_refresh_feed.setVisibility(View.VISIBLE);
		}

	}

	public void loadDataFail() {

	}

	public void loadDataSuccess() {

		if (listData.size() > 0 && listFeedFeature.size() > 0
				&& listFeedMostView.size() > 0) {
			indicator_loading_feed.setVisibility(View.GONE);
			adapter.notifyDataSetChanged();
			for (int i = 0; i < adapter.getGroupCount(); i++)
				listView.expandGroup(i);

			header.setVisibility(View.VISIBLE);

			listPager.clear();
			listPager.addAll(listFeedFeature);
			mPagerAdapter.notifyDataSetChanged();
			return;
		}

		if (passGetFeature && passGetHomeData && passGetMostView) {

			if (listData.size() == 0 || listFeedFeature.size() == 0
					|| listFeedMostView.size() == 0) {
				indicator_loading_feed.setVisibility(View.GONE);
				indicator_refresh_feed.setVisibility(View.VISIBLE);
			}

			passGetFeature = false;
			passGetHomeData = false;
			passGetMostView = false;

		}

	}

	@Override
	public void onRefreshStarted(View view) {
		viewPagerCallback.onFreezeViewPager();
		getFeed();
	}

	AsyncHttpResponseHandler featureHandler = new AsyncHttpResponseHandler() {

		@Override
		public void onSuccess(int arg0, Header[] arg1, byte[] arg2) {
			String result = new String(arg2);
			parser = GeneralParser.createInstance(Type.Post);
			List<GeneralModel> newData = parser.parseData(result);

			if (newData.size() == 0)
				return;

			listFeedFeature.clear();
			listFeedFeature.addAll(newData);

		}

		@Override
		public void onFailure(int arg0, Header[] arg1, byte[] arg2,
				Throwable arg3) {
		}

		public void onFinish() {
			passGetFeature = true;
			loadDataSuccess();
		};

	};

	AsyncHttpResponseHandler mostViewHandler = new AsyncHttpResponseHandler() {

		@Override
		public void onSuccess(int arg0, Header[] arg1, byte[] arg2) {
			String result = new String(arg2);
			parser = GeneralParser.createInstance(Type.Post);
			List<GeneralModel> newData = parser.parseData(result);

			if (newData.size() == 0)
				return;

			listFeedMostView.clear();
			listFeedMostView.addAll(newData);

			loadDataSuccess();
		}

		@Override
		public void onFailure(int arg0, Header[] arg1, byte[] arg2,
				Throwable arg3) {
			Log.e("Errorrrrr", arg3.toString());
		}

		public void onFinish() {
			passGetMostView = true;
			loadDataSuccess();
		}

	};

}
